<!--
@ 作者: 阿拉丁矿工 黄传鸿 <hchhyzc@foxmail.com>
-->
<template>
  <div class="center">
    <!-- 菜单工具条  图元数据-->
    <div class="h_heard">
      <div class="h_heard_left_icon"></div>
      <div class="h_heard_midol">图元数据</div>
      <div class="h_heard_right">
        <div class="h_flex_row_center">
          <!-- 新建 -->
          <div style="width: 10px"></div>
          <NTooltip placement="bottom" trigger="hover">
            <template #trigger>
              <svg class="h_tool_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" :width="IconSize"
                :height="IconSize" viewBox="0 0 1024 1024" v-html="onGetDataManagerIcon('dataAddIcon')"
                @click="onpelDataAdd"></svg>
            </template>
            <span>新建</span>
          </NTooltip>
          <!-- 删除 -->
          <div style="width: 10px"></div>
          <NTooltip placement="bottom" trigger="hover">
            <template #trigger>
              <svg class="h_tool_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" :width="IconSize"
                :height="IconSize" viewBox="0 0 1024 1024" v-html="onGetDataManagerIcon('dataDeleteIcon')"
                @click="onpelDataDelete"></svg>
            </template>
            <span>删除</span>
          </NTooltip>
          <!-- 全部删除 -->
          <div style="width: 10px"></div>
          <NTooltip placement="bottom" trigger="hover">
            <template #trigger>
              <svg class="h_tool_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" :width="IconSize"
                :height="IconSize" viewBox="0 0 1024 1024" v-html="onGetDataManagerIcon('dataSetAllDeleteIcon')"
                @click="onpelDataDeleteAll"></svg>
            </template>
            <span>全部删除</span>
          </NTooltip>
          <!-- 下载 -->
          <div style="width: 10px"></div>
          <NTooltip placement="bottom" trigger="hover">
            <template #trigger>
              <svg class="h_tool_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" :width="IconSize"
                :height="IconSize" viewBox="0 0 1024 1024" v-html="onGetDataManagerIcon('dataSetGetIcon')"
                @click="onpelDataDownload"></svg>
            </template>
            <span>下载</span>
          </NTooltip>

          <!-- 保存 -->
          <div style="width: 10px"></div>
          <NTooltip placement="bottom" trigger="hover">
            <template #trigger>
              <svg class="h_tool_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" :width="IconSize"
                :height="IconSize" viewBox="0 0 1024 1024" v-html="onGetDataManagerIcon('dataSetSaveIcon')"
                @click="onProjectSave()"></svg>
            </template>
            <span>保存</span>
          </NTooltip>

          <!-- 导入 -->
          <div style="width: 10px"></div>
          <NTooltip placement="bottom" trigger="hover">
            <template #trigger>
              <svg class="h_tool_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" :width="IconSize"
                :height="IconSize" viewBox="0 0 1024 1024" v-html="onGetDataManagerIcon('dataInExcelIcon')"
                @click="onOpenFileDialog"></svg>
            </template>
            <span>导入Excel表格</span>
          </NTooltip>

          <!-- 导出 -->
          <div style="width: 10px"></div>
          <NTooltip placement="bottom" trigger="hover">
            <template #trigger>
              <svg class="h_tool_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" :width="IconSize"
                :height="IconSize" viewBox="0 0 1024 1024" v-html="onGetDataManagerIcon('dataOutExcelIcon')"
                @click="onpelDataLeadingOut"></svg>
            </template>
            <span>导出Excel表格</span>
          </NTooltip>
          <div style="width: 10px"></div>
        </div>
      </div>
    </div>
    <!-- 页面更改插槽 -->
    <slot name="pageChange"></slot>
    <!-- 中间窗体 -->
    <div class="center_content">
      <!-- 数据表格 -->
      <n-data-table :columns="Columns" :data="pelData" :max-height="500" :pagination="Pagination"
        :row-props="onSelectRow" />
    </div>
    <slot name="down-clint">
    </slot>
    <!-- 文件导入 -->
    <input type="file" style="display: none" ref="fileRef" @change="onpelDataLeadingIn" />
  </div>
</template>

<script setup lang="ts">
/* ================================================================================================ */
// 🍀引入 ★
/* ================================================================================================ */
import { h, ref, reactive, computed, watch, onMounted } from "vue";
import axios from "axios";
import * as XLSX from "xlsx";
import type { DataTableColumns } from 'naive-ui';
import { useMessage } from 'naive-ui';
import { NTag, NInput, NSelect, NColorPicker, NInputNumber } from "naive-ui";

/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
// 🐸 图元端函数引入
/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
import {
  onGetDataManagerIcon,
  onProjectSave,
  onCreatePelDataOpt, // 创建 图元数据 选项
  onReadExcelFile, // 根据sheet索引读取Excel文件中的数据
  onRecordLog, // 日志处理器
  onGetUUID,// 获取UUID
  onActionRightNavigation,
} from "@/functions";

/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
// 🐸 引入存储
/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
import { useMenuStore } from "@/store/menuStore"; // 菜单
import { useCanvasStore } from "@/store/canvasStore"; // 画布
import { useProjectStore } from "@/store/projectStore"; // 工程
import { useStaticStore } from "@/store/staticStore"; // 静态
import { useWorkStore } from "@/store/workStore"; // 工作数据

/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
// 🐸 使用存储
/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
const menuStore = useMenuStore(); // 菜单
const canvasStore = useCanvasStore(); // 画布
const projectStore = useProjectStore(); // 工程
const staticStore = useStaticStore(); // 静态
const workStore = useWorkStore(); // 设备数据
const message = useMessage()// 消息

/* ================================================================================================ */
//                                数据 ★
/* ================================================================================================ */
/** 图元数据 */
let pelData = computed(() => workStore.pelData);
/** 设备数据读选项 */
const readEquipDataOpt = computed(() => canvasStore.readEquipDataOpt);

/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
// 🐸 从静态存储 引入 选项
/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
/** 颜色选项卡 */
const colorOpt = staticStore.colorOpt;
/** 变量类型选项:0-JSON数据;1-单行文本;2-颜色; */
const valTypeOpt = staticStore.valTypeOpt;
/** 图标尺寸 */
const IconSize = 30;
/** 文件参数 */
let fileRef = ref();

/** 行数据定义 */
type pelDataType = {
  pelDataId: string   // 图元数据_id;
  pelDataDescr: string // 图元数据_描述;
  pelDataLabel: string // 图元数据_标签名;
  pelDataType: number  // 图元数据_类型:0-JSON数据;1-单行文本;2-颜色;
  pelDataVal:string    // 图元数据_变量值;
  equipDataId: string  // 设备数据_id;
};

/** 列标 */
let Columns: DataTableColumns<pelDataType> = [
  // 图元数据_描述 pelDataDescr
  {
    title: "描述",
    key: "pelDataDescr",
    sorter: "default",
    resizable: true,
    minWidth: 100,
    maxWidth: 500,
    render(row, index) {
      return h(NInput, {
        value: row.pelDataDescr,
        onUpdateValue(v) {
          workStore.pelData[index].pelDataDescr = v;
        },
      });
    },
  },
  // 图元数据_标签名 pelDataLabel
  {
    title: "标签名",
    key: "pelDataLabel",
    sorter: "default",
    resizable: true,
    minWidth: 100,
    maxWidth: 500,
    render(row, index) {
      return h(NInput, {
        value: row.pelDataLabel,
        onUpdateValue(v) {
          workStore.pelData[index].pelDataLabel = v;
        },
      });
    },
  },
  // 图元数据_类型:0-JSON数据;1-单行文本;2-颜色; pelDataType
  {
    title: "类型",
    key: "pelDataType",
    sorter: "default",
    resizable: true,
    minWidth: 80,
    maxWidth: 200,
    render(row, index) {
      return h(NSelect, {
        value: row.pelDataType,
        options: valTypeOpt,
        onUpdateValue(v) {
          workStore.pelData[index].pelDataType = v;
        },
      });
    },
  },
  // 设备数据_id equipDataId
  {
    title: "连接设备",
    key: "equipDataId",
    sorter: "default",
    resizable: true,
    minWidth: 80,
    maxWidth: 200,
    render(row, index) {
      if (workStore.pelData[index].pelDataType === 1/*文本数据*/) {
        return h(NSelect, {
          value: row.equipDataId,
          options: readEquipDataOpt.value,
          onUpdateValue(v) {
            workStore.pelData[index].equipDataId = v;
          },
        });
      }

    },
  },
  // 图元数据_变量值; pelDataVal
  {
    title: "变量值",
    key: "pelDataVal",
    sorter: "default",
    resizable: true,
    minWidth: 100,
    maxWidth: 500,
    render(row, index) {
      if (workStore.pelData[index].pelDataType === 0/*JSON数据*/) {
        return h('div', workStore.pelData[index].pelDataVal);
      }
      if (workStore.pelData[index].pelDataType === 1/*文本数据*/) {
        return h(NInput, {
          value: row.pelDataVal,
          onUpdateValue(v) {
            workStore.pelData[index].pelDataVal = v;
          },
        });
      }
      if (workStore.pelData[index].pelDataType === 2/*颜色数据*/) {
        return h(NColorPicker, {
          value: row.pelDataVal,
          actions: ["confirm"],
          modes: ["rgb"],
          swatches: colorOpt,
          onUpdateValue(v) {
            workStore.pelData[index].pelDataVal = v;
          },
        });
      }
    },
  },
];

/** 分页 */
let Pagination = { pageSize: 1000 };
/* ================================================================================================ */
//                                函数 ★
/* ================================================================================================ */

/** 选择行 */
const onSelectRow = (Row: pelDataType) => {
  return {
    onClick: () => {
     // console.log("§ 选择行")
     // console.log(Row)
      /** ★ 赋值-选择的行数据 */
      canvasStore.selectedPelData = Row;
      onActionRightNavigation('RightPelData')   //激活右框导航
    },
  };
};

/** 图元数据-添加 */
const onpelDataAdd = () => {
 // console.log("§ 图元数据-添加")
  /** ★ 添加数据 */
  let AddData = {
    pelDataId: "sid" + onGetUUID(), // 图元数据_id
    pelDataDescr: "图元包JSON数据", // 图元数据_描述
    pelDataLabel: "json",          // 图元数据_标签名
    pelDataType: 1,                // 图元数据_类型:0-JSON数据;1-单行文本;2-颜色;
    pelDataVal: '10',              // 图元数据值;
    equipDataId: "none",           // 设备数据_id
  };

  /** ★ 添加 */
  workStore.pelData.push(AddData);
  /** ★ 清空-选择的行数据 */
  canvasStore.selectedPelData = AddData;
  message.success("添加图元数据，成功")
};

/** 图元数据-删除 */
const onpelDataDelete = () => {
 // console.log("§ 图元数据-删除")
 // console.log(Store.selectedPelData)

  /** ★ 查找id */
  let findId = String(canvasStore.selectedPelData.pelDataId);
 // console.log(id)

  /** ★ 根据id删除元素 */
  let Attribute = JSON.parse(JSON.stringify(workStore.pelData));
 // console.log(Attribute)
  for (let index = 0; index < Attribute.length; index++) {
    const element = Attribute[index];
    if (String(element.pelDataId) === findId) {
      Attribute.splice(index, 1);
    }
  }

 // console.log(Attribute)
  /** ★ 清空数据 */
  canvasStore.selectedPelData = [];
  workStore.pelData = [];
  /** ★ 赋值-图元数据 */
  workStore.pelData = Attribute;
  message.success("删除图元数据，成功")
};

/** 图元数据-删除全部 */
const onpelDataDeleteAll = () => {
 // console.log("§ 图元数据-删除全部")
  workStore.pelData = [];
  message.success("删除全部图元数据，成功")
};

/** 图元数据-下载 */
const onpelDataDownload = () => {
 // console.log("§ 图元数据-下载")
  /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  // 🐸 发送-工程数据
  /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  axios({
    url: `/api/HCIOT?query=getpelData`,
    method: "get",
  })
    .then((response: any) => {
      if (response.status === 200) {
        /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
        // 🐸 转储- 图元数据存储
        /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
       // console.log(response.data)
        workStore.pelData = response.data;

        /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
        // 🐸 提示 记录到日志
        /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
        onRecordLog("获取 图元数据 成功");
        message.success("获取成功");
      } else {
        onRecordLog("获取 图元数据 失败");
        message.success("获取 图元数据 失败");
      }
    })
    .catch((error: any) => {
     // console.log("故障")
      onRecordLog("获取 图元数据 失败");
      message.success("获取 图元数据 失败");
    });
};

/** 图元数据-导出 */
const onpelDataLeadingOut = () => {
 // console.log("§ 图元数据-导出")
  const ws = XLSX.utils.json_to_sheet(workStore.pelData);
  const wb = XLSX.utils.book_new();
  const fileName = "图元数据.xlsx";
  XLSX.utils.book_append_sheet(wb, ws, "图元数据");
  XLSX.writeFile(wb, fileName);
  message.success("导出图元数据，成功")
};

/** 打开文件对话框 */
const onOpenFileDialog = () => {
 // console.log("打开文件对话框");
 // console.log(fileRef.value);
  fileRef.value.dispatchEvent(new MouseEvent("click"));
};

/**  图元数据-导入 */
const onpelDataLeadingIn = () => {
 // console.log("图元数据-导入");
 // console.log(fileRef)
 // console.log(fileRef.value.files[0])
  let f = fileRef.value.files[0];
  workStore.pelData = onReadExcelFile(f, 0);
  message.success("导入图元数据，成功")
};

/* ================================================================================================ */
//                                ★ 钩子函数_挂载后
/* ================================================================================================ */
onMounted(() => {
 // console.log("钩子函数_挂载后")
  onCreatePelDataOpt(); //创建 图元数据 选项

});

</script>

<style lang="scss" scoped>
/* 引入共用css */
@import "@/assets/h.scss";

.center {
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.center_content {
  flex: 1;
}
</style>
